<template>
  <div class="code-editor">
    <!-- 编辑器头部 -->
    <div class="editor-header">
      <div class="header-left">
        <div class="problem-info">
          <span class="problem-number">第{{ problem.id }}题</span>
          <span class="problem-title">{{ problem.title }}</span>
          <el-tag :type="getDifficultyType(problem.difficulty)" size="small">
            {{ problem.difficulty }}
          </el-tag>
        </div>
      </div>
      
      <div class="header-right">
        <el-select v-model="selectedLanguage" @change="handleLanguageChange">
          <el-option label="JavaScript" value="javascript" />
          <el-option label="Python" value="python" />
          <el-option label="Java" value="java" />
          <el-option label="C++" value="cpp" />
          <el-option label="Go" value="go" />
        </el-select>
        
        <el-button @click="resetCode">
          <el-icon><Refresh /></el-icon>
          重置代码
        </el-button>
        
        <el-button @click="viewProblem">
          <el-icon><Document /></el-icon>
          查看题目
        </el-button>
      </div>
    </div>

    <!-- 编辑器主体 -->
    <div class="editor-main">
      <!-- 左侧：代码编辑器 -->
      <div class="editor-panel">
        <div class="editor-toolbar">
          <div class="toolbar-left">
            <span class="editor-title">代码编辑器</span>
            <span class="language-indicator">{{ getLanguageDisplay(selectedLanguage) }}</span>
          </div>
          
          <div class="toolbar-right">
            <el-button size="small" @click="formatCode">
              <el-icon><Magic /></el-icon>
              格式化
            </el-button>
            <el-button size="small" @click="toggleFullscreen">
              <el-icon><FullScreen /></el-icon>
              全屏
            </el-button>
          </div>
        </div>
        
        <div class="code-editor-container" ref="editorContainer">
          <textarea 
            v-model="code"
            class="code-textarea"
            :placeholder="getCodeTemplate()"
            @input="handleCodeChange"
          ></textarea>
        </div>
        
        <div class="editor-footer">
          <div class="footer-left">
            <span class="code-stats">
              行数: {{ codeLines }} | 字符: {{ codeLength }}
            </span>
          </div>
          
          <div class="footer-right">
            <el-button @click="runCode" :loading="running">
              <el-icon><CaretRight /></el-icon>
              运行代码
            </el-button>
            <el-button type="primary" @click="submitCode" :loading="submitting">
              <el-icon><Upload /></el-icon>
              提交代码
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 右侧：测试用例和结果 -->
      <div class="test-panel">
        <el-tabs v-model="activeTab" class="test-tabs">
          <!-- 测试用例 -->
          <el-tab-pane label="测试用例" name="testcases">
            <div class="testcases-content">
              <div class="testcase-selector">
                <el-radio-group v-model="selectedTestcase" @change="handleTestcaseChange">
                  <el-radio-button 
                    v-for="(testcase, index) in testcases" 
                    :key="index"
                    :label="index"
                  >
                    用例 {{ index + 1 }}
                  </el-radio-button>
                </el-radio-group>
              </div>
              
              <div class="testcase-details">
                <div class="testcase-input">
                  <div class="section-title">输入</div>
                  <div class="input-content">
                    <pre>{{ testcases[selectedTestcase]?.input }}</pre>
                  </div>
                </div>
                
                <div class="testcase-output">
                  <div class="section-title">预期输出</div>
                  <div class="output-content">
                    <pre>{{ testcases[selectedTestcase]?.expectedOutput }}</pre>
                  </div>
                </div>
                
                <div class="testcase-actions">
                  <el-button @click="runSingleTest" :loading="runningTest">
                    运行此用例
                  </el-button>
                  <el-button @click="addCustomTest">
                    添加测试用例
                  </el-button>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <!-- 运行结果 -->
          <el-tab-pane label="运行结果" name="result">
            <div class="result-content">
              <div v-if="!runResult" class="no-result">
                <div class="no-result-icon">
                  <el-icon><Monitor /></el-icon>
                </div>
                <div class="no-result-text">
                  <h3>暂无运行结果</h3>
                  <p>点击"运行代码"查看执行结果</p>
                </div>
              </div>
              
              <div v-else class="result-details">
                <div class="result-status" :class="runResult.status">
                  <div class="status-icon">
                    <el-icon v-if="runResult.status === 'success'"><CircleCheck /></el-icon>
                    <el-icon v-else><CircleClose /></el-icon>
                  </div>
                  <div class="status-text">
                    {{ getResultStatusText(runResult.status) }}
                  </div>
                </div>
                
                <div class="result-info" v-if="runResult.status === 'success'">
                  <div class="info-item">
                    <span class="label">执行时间:</span>
                    <span class="value">{{ runResult.runtime }}ms</span>
                  </div>
                  <div class="info-item">
                    <span class="label">内存消耗:</span>
                    <span class="value">{{ runResult.memory }}MB</span>
                  </div>
                </div>
                
                <div class="result-output">
                  <div class="section-title">输出结果</div>
                  <div class="output-content">
                    <pre>{{ runResult.output }}</pre>
                  </div>
                </div>
                
                <div class="result-error" v-if="runResult.error">
                  <div class="section-title">错误信息</div>
                  <div class="error-content">
                    <pre>{{ runResult.error }}</pre>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <!-- 提交记录 -->
          <el-tab-pane label="提交记录" name="submissions">
            <div class="submissions-content">
              <div v-if="submissions.length === 0" class="no-submissions">
                <EmptyState
                  image="/images/empty-submissions.svg"
                  title="暂无提交记录"
                  description="提交代码后可以在这里查看记录"
                />
              </div>
              
              <div v-else class="submissions-list">
                <div 
                  v-for="submission in submissions" 
                  :key="submission.id"
                  class="submission-item"
                >
                  <div class="submission-header">
                    <div class="submission-time">{{ formatDateTime(submission.submittedAt) }}</div>
                    <div class="submission-status" :class="getStatusClass(submission.status)">
                      {{ getStatusText(submission.status) }}
                    </div>
                  </div>
                  
                  <div class="submission-details">
                    <div class="detail-item">
                      <span class="label">语言:</span>
                      <span class="value">{{ submission.language }}</span>
                    </div>
                    <div class="detail-item" v-if="submission.runtime">
                      <span class="label">执行时间:</span>
                      <span class="value">{{ submission.runtime }}ms</span>
                    </div>
                    <div class="detail-item" v-if="submission.memory">
                      <span class="label">内存消耗:</span>
                      <span class="value">{{ submission.memory }}MB</span>
                    </div>
                  </div>
                  
                  <div class="submission-actions">
                    <el-button size="small" @click="viewSubmissionCode(submission)">
                      查看代码
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 自定义测试用例对话框 -->
    <el-dialog
      v-model="showCustomTestDialog"
      title="添加自定义测试用例"
      width="500px"
    >
      <div class="custom-test-form">
        <div class="form-item">
          <label>输入:</label>
          <el-input
            v-model="customTest.input"
            type="textarea"
            :rows="3"
            placeholder="请输入测试数据"
          />
        </div>
        
        <div class="form-item">
          <label>预期输出:</label>
          <el-input
            v-model="customTest.expectedOutput"
            type="textarea"
            :rows="3"
            placeholder="请输入预期输出"
          />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showCustomTestDialog = false">取消</el-button>
        <el-button type="primary" @click="saveCustomTest">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { 
  Refresh, Document, Magic, FullScreen, CaretRight, Upload,
  Monitor, CircleCheck, CircleClose
} from '@element-plus/icons-vue'
import EmptyState from '@/components/global/EmptyState.vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()

// 响应式数据
const selectedLanguage = ref('javascript')
const code = ref('')
const activeTab = ref('testcases')
const selectedTestcase = ref(0)
const running = ref(false)
const submitting = ref(false)
const runningTest = ref(false)
const runResult = ref(null)
const showCustomTestDialog = ref(false)
const editorContainer = ref(null)

// 题目数据
const problem = ref({
  id: 1,
  title: '两数之和',
  difficulty: '简单'
})

// 测试用例
const testcases = ref([
  {
    input: 'nums = [2,7,11,15], target = 9',
    expectedOutput: '[0,1]'
  },
  {
    input: 'nums = [3,2,4], target = 6',
    expectedOutput: '[1,2]'
  },
  {
    input: 'nums = [3,3], target = 6',
    expectedOutput: '[0,1]'
  }
])

// 自定义测试用例
const customTest = ref({
  input: '',
  expectedOutput: ''
})

// 提交记录
const submissions = ref([])

// 计算属性
const codeLines = computed(() => {
  return code.value.split('\n').length
})

const codeLength = computed(() => {
  return code.value.length
})

// 方法
const getDifficultyType = (difficulty) => {
  const types = {
    '简单': 'success',
    '中等': 'warning',
    '困难': 'danger'
  }
  return types[difficulty] || 'info'
}

const getLanguageDisplay = (language) => {
  const displays = {
    'javascript': 'JavaScript',
    'python': 'Python',
    'java': 'Java',
    'cpp': 'C++',
    'go': 'Go'
  }
  return displays[language] || language
}

const getCodeTemplate = () => {
  const templates = {
    'javascript': `/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    // 在这里编写你的代码
};`,
    'python': `def twoSum(nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """
    # 在这里编写你的代码
    pass`,
    'java': `class Solution {
    public int[] twoSum(int[] nums, int target) {
        // 在这里编写你的代码
        return new int[0];
    }
}`,
    'cpp': `class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        // 在这里编写你的代码
        return {};
    }
};`,
    'go': `func twoSum(nums []int, target int) []int {
    // 在这里编写你的代码
    return nil
}`
  }
  return templates[selectedLanguage.value] || ''
}

const getResultStatusText = (status) => {
  const texts = {
    'success': '运行成功',
    'error': '运行错误',
    'timeout': '运行超时'
  }
  return texts[status] || '未知状态'
}

const getStatusClass = (status) => {
  const classes = {
    'accepted': 'success',
    'wrong_answer': 'error',
    'time_limit_exceeded': 'warning'
  }
  return classes[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    'accepted': '通过',
    'wrong_answer': '答案错误',
    'time_limit_exceeded': '超时'
  }
  return texts[status] || '未知'
}

const formatDateTime = (date) => {
  return new Date(date).toLocaleString('zh-CN')
}

const handleLanguageChange = (language) => {
  selectedLanguage.value = language
  code.value = getCodeTemplate()
  ElMessage.success(`已切换到 ${getLanguageDisplay(language)}`)
}

const handleCodeChange = () => {
  // 自动保存代码到本地存储
  localStorage.setItem(`code_${problem.value.id}_${selectedLanguage.value}`, code.value)
}

const handleTestcaseChange = (index) => {
  selectedTestcase.value = index
}

const resetCode = () => {
  code.value = getCodeTemplate()
  ElMessage.success('代码已重置')
}

const formatCode = () => {
  ElMessage.info('代码格式化功能开发中...')
}

const toggleFullscreen = () => {
  if (document.fullscreenElement) {
    document.exitFullscreen()
  } else {
    editorContainer.value?.requestFullscreen()
  }
}

const runCode = async () => {
  if (!code.value.trim()) {
    ElMessage.warning('请先编写代码')
    return
  }
  
  running.value = true
  try {
    // 模拟代码运行
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    runResult.value = {
      status: 'success',
      runtime: Math.floor(Math.random() * 100) + 50,
      memory: Math.floor(Math.random() * 10) + 15,
      output: '[0,1]'
    }
    
    activeTab.value = 'result'
    ElMessage.success('代码运行完成')
  } catch (error) {
    runResult.value = {
      status: 'error',
      error: '运行时错误：数组越界'
    }
    ElMessage.error('代码运行失败')
  } finally {
    running.value = false
  }
}

const submitCode = async () => {
  if (!code.value.trim()) {
    ElMessage.warning('请先编写代码')
    return
  }
  
  submitting.value = true
  try {
    // 模拟代码提交
    await new Promise(resolve => setTimeout(resolve, 3000))
    
    const newSubmission = {
      id: Date.now(),
      status: 'accepted',
      language: getLanguageDisplay(selectedLanguage.value),
      runtime: Math.floor(Math.random() * 100) + 50,
      memory: Math.floor(Math.random() * 10) + 15,
      submittedAt: new Date()
    }
    
    submissions.value.unshift(newSubmission)
    activeTab.value = 'submissions'
    
    ElMessage.success('代码提交成功！')
  } catch (error) {
    ElMessage.error('代码提交失败')
  } finally {
    submitting.value = false
  }
}

const runSingleTest = async () => {
  runningTest.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('测试用例运行完成')
  } finally {
    runningTest.value = false
  }
}

const addCustomTest = () => {
  showCustomTestDialog.value = true
}

const saveCustomTest = () => {
  if (!customTest.value.input.trim()) {
    ElMessage.warning('请输入测试数据')
    return
  }
  
  testcases.value.push({
    input: customTest.value.input,
    expectedOutput: customTest.value.expectedOutput
  })
  
  customTest.value = { input: '', expectedOutput: '' }
  showCustomTestDialog.value = false
  ElMessage.success('自定义测试用例已添加')
}

const viewProblem = () => {
  router.push(`/coding/problem/${problem.value.id}`)
}

const viewSubmissionCode = (submission) => {
  ElMessage.info(`查看提交代码：${submission.id}`)
}

// 生命周期
onMounted(() => {
  // 加载保存的代码
  const savedCode = localStorage.getItem(`code_${problem.value.id}_${selectedLanguage.value}`)
  if (savedCode) {
    code.value = savedCode
  } else {
    code.value = getCodeTemplate()
  }
  
  // 监听编辑器设置变化
  window.addEventListener('editor-language-change', (e) => {
    selectedLanguage.value = e.detail
    handleLanguageChange(e.detail)
  })
})

onUnmounted(() => {
  // 清理事件监听器
  window.removeEventListener('editor-language-change', () => {})
})
</script>

<style lang="scss" scoped>
.code-editor {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color-page);
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: white;
  border-bottom: 1px solid var(--el-border-color-extra-light);
}

.header-left {
  .problem-info {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .problem-number {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
    
    .problem-title {
      font-size: 16px;
      font-weight: 500;
      color: var(--el-text-color-primary);
    }
  }
}

.header-right {
  display: flex;
  gap: 12px;
  align-items: center;
  
  .el-select {
    width: 120px;
  }
}

.editor-main {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.editor-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  border-right: 1px solid var(--el-border-color-extra-light);
}

.editor-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background: var(--el-fill-color-extra-light);
  border-bottom: 1px solid var(--el-border-color-extra-light);
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
  
  .editor-title {
    font-size: 14px;
    font-weight: 500;
    color: var(--el-text-color-primary);
  }
  
  .language-indicator {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    background: var(--el-color-primary-light-9);
    padding: 2px 6px;
    border-radius: 3px;
  }
}

.toolbar-right {
  display: flex;
  gap: 8px;
}

.code-editor-container {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.code-textarea {
  width: 100%;
  height: 100%;
  border: none;
  padding: 16px;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 14px;
  line-height: 1.5;
  resize: none;
  outline: none;
  background: #1e1e1e;
  color: #d4d4d4;
}

.editor-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background: var(--el-fill-color-extra-light);
  border-top: 1px solid var(--el-border-color-extra-light);
}

.footer-left {
  .code-stats {
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }
}

.footer-right {
  display: flex;
  gap: 8px;
}

.test-panel {
  width: 400px;
  background: white;
  display: flex;
  flex-direction: column;
}

.test-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
  
  :deep(.el-tabs__content) {
    flex: 1;
    overflow: hidden;
  }
  
  :deep(.el-tab-pane) {
    height: 100%;
    overflow-y: auto;
  }
}

.testcases-content {
  padding: 16px;
}

.testcase-selector {
  margin-bottom: 16px;
}

.testcase-details {
  .testcase-input,
  .testcase-output {
    margin-bottom: 16px;
    
    .section-title {
      font-size: 14px;
      font-weight: 500;
      margin-bottom: 8px;
      color: var(--el-text-color-primary);
    }
    
    .input-content,
    .output-content {
      background: var(--el-fill-color-extra-light);
      border-radius: 6px;
      padding: 12px;
      
      pre {
        margin: 0;
        font-family: 'Consolas', 'Monaco', monospace;
        font-size: 13px;
        white-space: pre-wrap;
        word-break: break-all;
      }
    }
  }
  
  .testcase-actions {
    display: flex;
    gap: 8px;
  }
}

.result-content {
  padding: 16px;
  height: 100%;
}

.no-result {
  text-align: center;
  padding: 40px 20px;
  
  .no-result-icon {
    font-size: 48px;
    color: var(--el-text-color-placeholder);
    margin-bottom: 16px;
  }
  
  .no-result-text {
    h3 {
      font-size: 16px;
      margin-bottom: 8px;
      color: var(--el-text-color-primary);
    }
    
    p {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
  }
}

.result-details {
  .result-status {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 16px;
    padding: 12px;
    border-radius: 6px;
    
    &.success {
      background: var(--el-color-success-light-9);
      color: var(--el-color-success);
    }
    
    &.error {
      background: var(--el-color-danger-light-9);
      color: var(--el-color-danger);
    }
    
    .status-icon {
      font-size: 18px;
    }
    
    .status-text {
      font-weight: 500;
    }
  }
  
  .result-info {
    margin-bottom: 16px;
    
    .info-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 4px;
      font-size: 14px;
      
      .label {
        color: var(--el-text-color-secondary);
      }
      
      .value {
        font-weight: 500;
        color: var(--el-text-color-primary);
      }
    }
  }
  
  .result-output,
  .result-error {
    margin-bottom: 16px;
    
    .section-title {
      font-size: 14px;
      font-weight: 500;
      margin-bottom: 8px;
      color: var(--el-text-color-primary);
    }
    
    .output-content,
    .error-content {
      background: var(--el-fill-color-extra-light);
      border-radius: 6px;
      padding: 12px;
      
      pre {
        margin: 0;
        font-family: 'Consolas', 'Monaco', monospace;
        font-size: 13px;
        white-space: pre-wrap;
      }
    }
    
    .error-content {
      background: var(--el-color-danger-light-9);
      color: var(--el-color-danger-dark-2);
    }
  }
}

.submissions-content {
  padding: 16px;
  height: 100%;
}

.no-submissions {
  text-align: center;
  padding: 40px 20px;
}

.submissions-list {
  .submission-item {
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 6px;
    padding: 12px;
    margin-bottom: 12px;
    
    .submission-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      
      .submission-time {
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }
      
      .submission-status {
        font-size: 12px;
        font-weight: 500;
        
        &.success {
          color: var(--el-color-success);
        }
        
        &.error {
          color: var(--el-color-danger);
        }
        
        &.warning {
          color: var(--el-color-warning);
        }
      }
    }
    
    .submission-details {
      margin-bottom: 8px;
      
      .detail-item {
        display: flex;
        justify-content: space-between;
        font-size: 12px;
        margin-bottom: 2px;
        
        .label {
          color: var(--el-text-color-secondary);
        }
        
        .value {
          color: var(--el-text-color-primary);
        }
      }
    }
    
    .submission-actions {
      text-align: right;
    }
  }
}

.custom-test-form {
  .form-item {
    margin-bottom: 16px;
    
    label {
      display: block;
      margin-bottom: 8px;
      font-weight: 500;
      color: var(--el-text-color-primary);
    }
  }
}

@media (max-width: 1024px) {
  .editor-main {
    flex-direction: column;
  }
  
  .test-panel {
    width: 100%;
    height: 300px;
    border-right: none;
    border-top: 1px solid var(--el-border-color-extra-light);
  }
  
  .header-right {
    flex-wrap: wrap;
    gap: 8px;
  }
}
</style>
